package com.doraemon.module.buyer.controller;

import com.doraemon.module.buyer.entity.ProductCategory;
import com.doraemon.module.buyer.entity.ProductInfo;
import com.doraemon.module.buyer.service.CategoryService;
import com.doraemon.module.buyer.service.ProductInfoService;
import com.doraemon.module.buyer.vo.ProductInfoVO;
import com.doraemon.module.buyer.vo.ProductVO;
import com.doraemon.module.buyer.vo.ReturnVO;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author doraemon
 * @date 2017/9/12
 */
@Api
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ReturnVO list() {
        //1.1获取所有上架的商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        //1.2获取上架商品的类目编号
        List<Integer> categoryTypes = productInfoList.stream().
                map(ProductInfo::getCategoryType).
                collect(Collectors.toList());
        //2.获取所有上架商品的类目
        List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(categoryTypes);
        //3.拼装ReturnVO
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory category : categoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(category.getCategoryType());
            productVO.setCategoryName(category.getCategoryName());
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList) {
                if (category.getCategoryType().equals(productInfo.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    //使用BeanUtils Copy属性
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }

        return ReturnVO.success(productVOList);
    }
}
